package site.zhanjingbo.HelloDB;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * JDBC 单元测试主管作业
 * @author swuzjb
 *
 */
public class JDBCHomework {
	
	static String DRIVER_NAME = "com.mysql.jdbc.Driver";
	static String DB_URL = "jdbc:mysql://localhost:3307/cloud_study?characterEncoding=utf8";
	static String DB_USER = "root";
	static String DB_PASSWORD = "";

	/**
	 * 通过ID读取商品表，输出对应商品的名称和库存数量
	 * @param id
	 */
	public static void findProductById(int id) {
		Connection conn = null;
		PreparedStatement ptmt = null;
		ResultSet rs = null;

		try {
			Class.forName(DRIVER_NAME);
			conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
			ptmt = conn.prepareStatement("select * from Product where Id=?");

			ptmt.setInt(1, id);

			rs = ptmt.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString("ProductName") + ":" + rs.getInt("Inventory"));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 调用测试
	 * @param args
	 */
	public static void main(String[] args) {
		findProductById(1);
	}
}
